package logic

import (
	"context"
	"fmt"
	"math/rand"
	"wechats/models/mysql"

	"wechats/wechatrpc/internal/svc"
	"wechats/wechatrpc/wechatrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *wechatrpc.LoginRequest) (*wechatrpc.LoginResponse, error) {
	// todo: add your logic here and delete this line

	var user mysql.User
	mysql.DB.Debug().Where("account = ?", in.Account).Find(&user)

	if user.ID == 0 {
		user = mysql.User{
			Account:   in.Account,
			Password:  in.Password,
			HeadImage: "http://t1l2h9yhv.hn-bkt.clouddn.com/img3.png",
			Name:      fmt.Sprintf("用户_%d", rand.Intn(10000)),
		}

		mysql.DB.Debug().Create(&user)
	} else {
		if in.Password != user.Password {
			return nil, fmt.Errorf("密码错误")
		}
	}

	return &wechatrpc.LoginResponse{
		UserId: int64(user.ID),
	}, nil
}
